package me.keiwu.user.service.impl;

import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.util.DateUtil;
import me.keiwu.pub.util.EntityUtil;
import me.keiwu.user.dao.MedalDao;
import me.keiwu.user.dao.MedalPresentDao;
import me.keiwu.user.dao.UserMedalDao;
import me.keiwu.user.domain.Medal;
import me.keiwu.user.domain.MedalPresent;
import me.keiwu.user.domain.UserMedal;
import me.keiwu.user.service.MedalService;
import me.keiwu.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kei on 30/01/2018.
 */
@Service
@Transactional
public class MedalServiceImpl implements MedalService {

    private Logger logger = LoggerFactory.getLogger(MedalServiceImpl.class);


    @Autowired
    private MedalDao medalDao;
    @Autowired
    private UserMedalDao userMedalDao;
    @Autowired
    private MedalPresentDao medalPresentDao;
    @Autowired
    private UserService userService;



    @Override
    public ResponseV2 exchangeMedal(Long userId, Integer medalId) {
        Medal medal = medalDao.findOne(medalId);
        if (medal == null) {
            logger.info("wrong medalId from client, userId={}, medalId={}", userId, medalId);
            return ResponseV2.fail("不存在该勋章");
        }

        if (userService.changeGold(userId, -Math.abs(medal.getCost()))) {
            UserMedal userMedal = new UserMedal();
            userMedal.setUserId(userId);
            userMedal.setMedalId(medalId);
            userMedal.setGetTime(DateUtil.getUnixTime());
            userMedalDao.save(userMedal);
            return ResponseV2.ok(medal);
        }
        return ResponseV2.fail("星币不足");
    }

    @Override
    public Page<Medal> findAllMedals(Long userId, int page, int size) {
        Specification<Medal> spec = (root, query, cb) -> {
            return cb.equal(root.get("shelve"), true);
        };
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<Medal> list = medalDao.findAll(spec, pageable);

        list.getContent().forEach(m -> {
            // 是否获得，展示等
            UserMedal um = userMedalDao.findByUserIdAndMedalId(userId, m.getId());
            if (um != null) {
                m.setGet(true);
                m.setDisplay(um.isDisplay());
            } else {
                m.setGet(false);
                m.setDisplay(false);
            }

            // 是否设置礼品信息
            MedalPresent mp = medalPresentDao.findByUserIdAndMedalId(userId, m.getId());
            if (mp != null) {
                m.setSetPresent(true);
            } else {
                m.setSetPresent(false);
            }

        });
        return list;
    }



    @Override
    public Page<Medal> findAllMedals(int page, int size) {
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        return medalDao.findAll(pageable);
    }

    @Override
    public ResponseV2 displayUserMedal(Long userId, Integer medalId, boolean display) {
        UserMedal um = userMedalDao.findByUserIdAndMedalId(userId, medalId);
        if (um == null) {
            return ResponseV2.fail("没有该勋章");
        }
        um.setDisplay(display);
        userMedalDao.save(um);
        return ResponseV2.ok(um);
    }

    @Override
    public Medal saveMedal(Integer medalId, String name, String url, Integer cost) {
        Medal medal = new Medal();
        medal.setId(medalId);
        medal.setName(name);
        medal.setUrl(url);
        medal.setCost(Math.abs(cost));
        medalDao.save(medal);
        return medal;
    }



    @Override
    public ResponseV2 medalPresentContact(Long userId, String nickName, Integer medalId, String name, String telephone, String address, String zip) {
        Medal medal = medalDao.findOne(medalId);
        if (medal == null) return ResponseV2.fail("没有该勋章");
        MedalPresent mp = medalPresentDao.findByUserIdAndMedalId(userId, medalId);
        if (mp != null) return ResponseV2.fail("一个勋章只能领取一次");
        mp = new MedalPresent();
        mp.setUserId(userId);
        mp.setNickName(nickName);
        mp.setMedalId(medalId);
        mp.setName(name);
        mp.setTelephone(telephone);
        mp.setAddress(address);
        mp.setZip(zip);
        medalPresentDao.save(mp);
        return ResponseV2.ok(mp);
    }


    @Override
    public Medal shelve(Integer medalId, boolean shelve) {
        Medal m = medalDao.findOne(medalId);
        if (m == null) return null;
        m.setShelve(shelve);
        medalDao.save(m);
        return m;
    }


    @Override
    public MedalPresent sendMedalPresent(Integer presentId) {
        MedalPresent mp = medalPresentDao.findOne(presentId);
        if (mp == null) return null;
        mp.setHasSent(true);
        medalPresentDao.save(mp);
        return mp;
    }

    @Override
    public Page<MedalPresent> listPresent(Integer page, Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<MedalPresent> list = medalPresentDao.findAll(pageable);
        list.getContent().forEach(mp -> mp.setMedal(medalDao.findOne(mp.getMedalId())));
        return list;
    }

    @Override
    public List<MedalPresent> listPresent() {
        List<MedalPresent> list = medalPresentDao.findAll();
        list.forEach(mp -> mp.setMedal(medalDao.findOne(mp.getMedalId())));
        return list;
    }


    @Override
    public MedalPresent presentDetail(Integer presentId) {
        return medalPresentDao.findOne(presentId);
    }
}
